import Taro, { Component,useMemo } from '@tarojs/taro'
import {View, Button, Text, Image, Swiper, SwiperItem,} from '@tarojs/components'
import './detailPage.scss';
import AppConfig from '../../config/appConfig';
import {TenThousandToStr,TimestampToTime,IsNullObject} from "../../utils/utils";
import {ChangePromotionUrl,GetPromotionDataStr} from '../../mode/promotionUrlCtr';
import Popular from '../popular/popular';
import taroUtils from '../../utils/taroUtils';
import appStore from "../../store/appStore";
import { AtToast, AtModal} from "taro-ui"
import {getLink} from '../../mode/modeCtr';
import viewUtil from "../../utils/viewUtil";
import {getTaoBaoConfig} from "../../mode/homeCtr";
const info = Taro.getSystemInfoSync()
const { windowHeight } = info

// import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from "taro-ui"

class DetailPage extends Component{

  config = {
    navigationBarTitleText: '商品详情',
    // "disableScroll": true   //静止页面滚动
  }
  state ={
    item:{},
    swiperH:0,
    isOpened:false,
    // similarItems:[]
  }
  constructor() {
    super()

  }

  componentWillMount (options) {
    console.log(appStore.appConfig.open)
    if (appStore.appConfig.open < 0){
      getTaoBaoConfig().then(res=>{
        this.start()
      })
    }else {
      this.start()
    }
  }

  start(){
    if (IsNullObject(this.$router.params.ShareItem) === true){
      // console.log(this.$router.params.item)
      this.setState({
        item:JSON.parse(this.$router.params.item)
      },()=>{

      })
    }else {
      this.setState({
        item:JSON.parse(decodeURIComponent(this.$router.params.ShareItem))
      },()=>{

      })
    }
  }

  componentDidMount () { }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  //获取swiper高度
  getHeight = (e) => {
    var winWid = Taro.getSystemInfoSync().windowWidth - 2*50;//获取当前屏幕的宽度
    var imgh = e.detail.height;//图片高度
    var imgw = e.detail.width;//图片宽度
    // console.log(imgh,imgw);
    var sH = winWid * imgh / imgw + "px"
    this.setState({
      swiperH: sH//设置高度
    },()=>{
      console.log(this.state.swiperH)
    })
  }


  /**
   * 点击领取
   * */
  //暂时屏蔽客服操作
  // onClickCoupon=()=>{
  //   ChangePromotionUrl(this.state.item).then(item=> {
  //     console.log("淘口令:"+item.Tpwd)
  //     console.log("优惠劵URL:"+item.CouponUrl)
  //     if (item.Tpwd !== ''){
  //       this.Coupon(item,item.Tpwd,"淘口令复制成功")
  //     }else {
  //       this.Coupon(item,item.CouponUrl,"优惠劵复制成功")
  //     }
  //   })
  // }
  //暂时屏蔽客服操作
  // Coupon(item,copyData,tip){
  //   wx.setClipboardData({
  //     data:copyData,
  //     success:function (res) {
  //       Taro.showToast({title:tip})
  //     }
  //   })
  //
  //   Taro.setClipboardData({
  //     data: copyData,
  //     success: function (res) {
  //       var  data = GetPromotionDataStr(item)
  //       wx.cloud.callFunction({
  //         // 云函数名称
  //         name: 'taokeApi',
  //         // 传给云函数的参数
  //         data: {
  //           myData:data
  //         },
  //       }).then(res => {
  //
  //       }).catch(console.error)
  //     }
  //   })
  // }

  /**
   * 点击领取直接复制
   * */
  onClickLingquNoOpen=()=>{
    viewUtil.ShowLoading(true,"请求数据中...")
    ChangePromotionUrl(this.state.item).then(item=> {
      viewUtil.ShowLoading(false)
      if (this.state.item.TypeFrom === AppConfig.TaoBao){
        this.setState({
          isOpened:true
        })
      }else {
          Taro.setClipboardData({
            data: getLink(item),
            success: function (res) {
              var  data = GetPromotionDataStr(item)
              wx.cloud.callFunction({
                // 云函数名称
                name: 'taokeApi',
                // 传给云函数的参数
                data: {
                  myData:data
                },
              }).then(res => {

              }).catch(console.error)
            }
          })
      }

    })
  }

  handleClose=()=>{}
  handleCancel=()=>{
    this.setState({
      isOpened:false
    })
  }
  handleConfirm=()=>{
    this.setState({
      isOpened:false
    })
    var  item = this.state.item
    if (item.Tpwd !== ''){
      wx.setClipboardData({
        data:item.Tpwd,
        success:function (res) {
          Taro.showToast({title:'复制成功'})
        }
      })
    }else {

      wx.setClipboardData({
        data:getLink(item),
        success:function (res) {
          Taro.showToast({title:'优惠劵复制成功'})
        }
      })
    }

  }

  BackToApp=()=>{


  }

  onShare=()=>{

    Taro.showShareMenu({
      withShareTicket: true
    })
  }

  onShareAppMessage (res) { //放在父组件上执行，子组件上不被执行！
    const ItemData = encodeURIComponent(JSON.stringify(this.state.item))
    const show={
      title: this.state.item.Title,
      desc:this.state.item.Desc,
      path: taroUtils.GetCurrentPageUrl(),
      success: function () {
        // 转发成功

      },
      fail: function () {
        // 转发失败

      }
    }
    // 来自页面内的按钮的转发
    if( res.from == 'button' ){
      var eData = res.target.dataset;
      // 此处可以修改 shareObj 中的内容
      show.path = taroUtils.GetCurrentPageUrl()+"?ShareItem="+ItemData;
    }
    return show
  }

  render () {
    var temp = this.state.item.TypeFrom === AppConfig.TaoBao ? <View></View>:<View className={'tuijiangliyouContain'}>
      <Text className={'zhuyi'}>注意:客服无反应，请回复1再重来领取!</Text>
    </View>

    return (
      <View>
        <View className={'bottomBtn'}>

          <Button className={"shareBtn"} openType='share'>
            <Text className='shareText'>分享</Text>
          </Button>

          {/*<Button*/}
          {/*  className={"shareBtn"}*/}
          {/*  sendMessageTitle={ this.state.item.Title} // 分享的客服会话标题*/}
          {/*  // sendMessageImg={shareInfo.shareImg ? shareInfo.shareImg : default_share_circle} // 分享的客服会话的封面图*/}
          {/*  sendMessagePath={this.state.item.CouponUrl} // 对应的需要分享到朋友圈的h5链接*/}
          {/*  sessionFrom={'wkbbapp'} // 暂时发现没啥用*/}
          {/*  openType="contact" // 必填，表示唤起客服会话*/}
          {/*  showMessageCard // 必填，唤起会话右下角的截图弹出*/}
          {/*  plain*/}
          {/*  onContact={(res) => {*/}
          {/*    console.error('onContact', res);*/}
          {/*  }}*/}
          {/*>*/}
          {/*  <Text className='shareText'>分享</Text>*/}
          {/*</Button>*/}


        </View>

        {/*轮播图*/}
        <Swiper
          className='test-h'
          indicatorColor='#999'
          indicatorActiveColor='#333'
          horizontal
          circular
          indicatorDots
          style={`height:${this.state.swiperH}`}
          autoplay>
          {
            this.state.item.goods_gallery_urls.map((imageSrc,index)=>{
              return(
                <SwiperItem  key={index}>
                  <View >
                    <Image onLoad={this.getHeight} className={'swiper-img'} style={`height:${this.state.swiperH}`}  src={imageSrc}></Image>
                  </View>
                </SwiperItem>

              )
            })
          }
        </Swiper>
        {/*描述*/}
        <View  className={'view_1'}>
          <View className={'text-1'}>
            <Text  style={{
              display: '-webkit-box',
              overflow: 'hidden',
              '-webkit-line-clamp': 3,
              '-webkit-box-orient': 'vertical',
              color: '#121212',
              textOverflow:"ellipsis",
              width: "100%",
              wordBreak:"break-word"
            }}>
              {/*<Text className={'text-1-jingping'}>*/}
              {/*{*/}
              {/*this.state.item.TypeFrom ===null?'':AppConfig.GetTypeStr(this.state.item.TypeFrom)*/}
              {/*}*/}
              {/*</Text>*/}
              {this.state.item.Title ? this.state.item.Title:this.state.item.ShortTitle}
            </Text>
          </View>
        </View>

        <View className={'view_2'}>
          <View className={'view_2_contain'}>
            <Text className={'juanhou'}>
              {
                appStore.appConfig.open >=1 ?'卷后价￥':''
              }

              <Text className={'juanhou-price'}>
                {this.state.item.EndPrice}
                <Text className={'juanhou-truePrice'}>
                  ￥{item.Price}
                </Text>

              </Text>
            </Text>
            {
              <Text className={'mouthSell'}>月销:{TenThousandToStr(this.state.item.SaleCount)}</Text>
            }
          </View>
        </View>
        {/*领卷*/}

        {
          appStore.appConfig.open >=1 ?(
            <View className={'view_3'}>
              <View className={'view_lingjuan'}>
                <View className={'lingjuan_1'}>
                  <Text className={'lingjuan_1-CouponMoney'}>
                    <Text className={'lingjuan_1-CouponMoney-yuan'}>{this.state.item.CouponMoney}</Text>
                    元优惠卷
                    {
                      this.state.item.frist_order > 0 ?(<Text >{this.state.item.frist_order}元礼金</Text>):<View/>
                    }
                  </Text>
                  {
                    this.state.item.CouponStartTime >0 ?(<Text className={'lingjuan_1-time'}>
                      使用期限: {TimestampToTime(this.state.item.CouponStartTime)} 至 {TimestampToTime(this.state.item.CouponEndTime)}
                    </Text>):<View/>
                  }

                </View>
                <View className={'lingjuan_2'}>
                  <Text className={'lingjuan_2-line'} >. . . . . . .</Text>
                </View>
                {/*<Button className={'lingjuan_3'} onClick={this.onClickLingquNoOpen} >*/}
                {/*  <Text className={'lingjuan_3-text'}>*/}
                {/*    立即领取*/}
                {/*  </Text>*/}
                {/*</Button>*/}
                {/*暂时屏蔽云函数和客服操作*/}
                {

                  this.state.item.TypeFrom !== AppConfig.TaoBao ?
                    <Button className={'lingjuan_3'} openType='contact' onContact={this.BackToApp} onClick={this.onClickLingquNoOpen} >
                      <Text className={'lingjuan_3-text'}>
                        立即领取
                      </Text>
                    </Button> :
                    <Button className={'lingjuan_3'} onClick={this.onClickLingquNoOpen} >
                      <Text className={'lingjuan_3-text'}>
                        立即领取
                      </Text>
                    </Button>

                }

              </View>
            </View>
          ):(<View></View>)

        }

        {/*暂时屏蔽云函数和客服操作*/}
        {
          temp
        }


        {/*推荐理由*/}
        {
          this.state.item.Desc === null ? <View/>:(
            <View className={'tuijiangliyouContain'}>
              <View className={'tuijiangliyouContain-contain'}>

                <Text className={'tuijiangliyouContain-text'}>
                  推荐理由:
                  <Text className={'tuijiangliyouContain-textCotain'}>
                    {this.state.item.Desc}
                  </Text>
                </Text>
              </View>
            </View>
          )
        }
        {/*猜你喜欢*/}
        <View className={'view_4_like'}>
          <View className={'view_4_like-line'}/>
          <Text className={'view_4_like-like_Text'}>猜你喜欢:</Text>
          {
            // this.state.similarItems === []?<View/> : (
            //   <Popular data={this.state.similarItems}></Popular>
            // )
            <Popular item={this.state.item}/>
          }

        </View>

        <AtModal
          isOpened={this.state.isOpened}
          title={"复制"}
          cancelText='取消'
          confirmText='复制'
          onClose={ this.handleClose }
          onCancel={ this.handleCancel }
          onConfirm={ this.handleConfirm }
          content={"复制:\n"+this.state.Tpwd+'\n\n\n'+'复制-->打开淘'}
        >

        </AtModal>

      </View>
    )
  }


}

export  default DetailPage
